package org.poptest.model;

import org.poptest.reflect.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.ListIterator;

/**
 * @author Alan Roche
 *         Date: 05/02/11
 *         Time: 22:41
 */
public class FieldNode extends AbstractNode<FieldNode> {
    private final Field field;

    public FieldNode(final TestInstance testInstance, final Field field) {
        super(testInstance);
        this.field = field;
    }


    public Object getValue() {
        return ReflectionUtils.getValue(testInstance.getInstance(), field);
    }

    public <T> T getValue(Class<T> expectedType) {
        return ReflectionUtils.getValue(testInstance.getInstance(), field, expectedType);
    }

    public String getName() {
        return field.getName();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;

        FieldNode fieldNode = (FieldNode) o;

        if (field != null ? !field.equals(fieldNode.field) : fieldNode.field != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (field != null ? field.hashCode() : 0);
        return result;
    }


    /**
     * Returns an iterator indexed just before this node.
     * Calling previous)_ returns the item before this node.
     * Calling next() returns this node
     */
    @Override
    protected ListIterator<FieldNode> getIteratorAtSelf() {
        return testInstance.fieldIterator(this);
    }

    public Field getField() {
        return field;
    }
}
